package org.destiny.swing.mapping;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import javax.swing.JPanel;

public class FormPane<T> extends JPanel {

	private static final long serialVersionUID = 1L;
	private Class<T> fromModelClass;

	private T formModel;
	private ArrayList<FormItemMapper> formItemMappers;

	public FormPane(Class<T> formModelClass) throws InstantiationException, IllegalAccessException {
		super(new GridBagLayout());
		this.fromModelClass = formModelClass;
		this.formModel = formModelClass.newInstance();
		load();
	}

	protected void load() {
		GridBagConstraints csts = new GridBagConstraints();
		try {
			for (Field field : fromModelClass.getDeclaredFields()) {
				FormItemMapper mapper  = FormMappingLoader.getDefaultMappingComponent(field);

				csts.gridx = 0;
				csts.gridy++;
				csts.anchor = GridBagConstraints.EAST;
				add(mapper.getJLabel(), csts);

				csts.gridx++;
				csts.anchor = GridBagConstraints.WEST;
				add(mapper.getInputComponent(), csts);
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}

	public T getFormModel() {

		return formModel;
	}

	public void setFormModel(T formModel) {
		this.formModel = formModel;
	}

}
